package com.intelligentmeterreadingsys.waterlist.reviewdata.activity;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.httpserver.UploadHttpClient;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.povo.WaterInfoVO;
import com.intelligentmeterreadingsys.report.activity.ReportNoRFIDActivity;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.CopyWaterNoRFIDActivity;
import com.intelligentmeterreadingsys.waterlist.copywater.activity.ImageSwitcherActivity;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;
import com.intelligentmeterreadingsys.waterlist.reviewdata.db.ReviewDataDao;

import dbhelper.XmlNameHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * RFID异常数据复查
 * @author king
 *
 */
public class ReviewNoRfidActivity extends Activity implements OnClickListener{
    public Button button1;// 拍照	
	public Button button2;// 保存
	public Button button3;// 上传
	public EditText edit1;// 复查刻度
	public EditText edit2;// 备注
	public TextView textview1;// 用户姓名
	public TextView textview2;// 水表编号
	public TextView textview3;// 水表地址
	public TextView textview4;//用水性质
	public TextView textview5;//水表中径
	public TextView textview6;// 上次抄表刻度	
	public TextView textview7;//用水量
	public String waterid;//水表ID
	public UserWaterVO water=null;
	public WaterInfoVO waterinfo=null;
	public ProgressDialog pd;// 读卡进度条
	public boolean isupload=false;
	public boolean issave=false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.review_water_query);
		init();
	}

	/**
	 * 初始化
	 */
	public void init(){
		TextView vie=(TextView)findViewById(R.id.reviewwater_query_textView1);
		vie.setText("RFID异常数据复查");
		button1=(Button)findViewById(R.id.review_query_paizhao);
		button2=(Button)findViewById(R.id.review_query_save);
		edit1=(EditText)findViewById(R.id.review_query_thismonthwater);
		edit2=(EditText)findViewById(R.id.review_query_desc);
		button3=(Button)findViewById(R.id.review_query_upload);
	    textview1=(TextView)findViewById(R.id.review_query_username);
	    textview2=(TextView)findViewById(R.id.review_query_waternumber);
	    textview3=(TextView)findViewById(R.id.review_query_wateradds);
	    textview4=(TextView)findViewById(R.id.review_query_waterproperties);
	    textview5=(TextView)findViewById(R.id.review_query_metercaliber);
	    textview6=(TextView)findViewById(R.id.review_query_opendegree);
	    textview7=(TextView)findViewById(R.id.review_query_usewater);
	    button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		edit1.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				
				if(water!=null){
					if(!TextUtils.isEmpty(s.toString())){
						Double usewater=Double.parseDouble(s.toString())-water.getLastmonthwater();
						
						textview7.setText(usewater+"");
						if(usewater<water.getAlarmlimit()|usewater>water.getLowalarmlimit()){
							textview7.setTextColor(Color.RED);
							//edit1.setTextColor(Color.RED);
						}else{
							//edit1.setTextColor(Color.BLACK);
							textview7.setTextColor(Color.BLACK);
						}
					}else{
						textview7.setText("");
					//	edit1.setTextColor(Color.BLACK);
						textview7.setTextColor(Color.BLACK);
						
					}
					
				}
				
			}
		});
		waterid=getIntent().getStringExtra("waterid");
		ReviewDataDao dao=new ReviewDataDao(this);
		water=dao.queryOneReview(null, waterid);
		dao.close();
		viewDate();
		
		
	}

	/**
	 * 展现数据
	 */

	public void viewDate(){		
		textview1.setText("");
		textview2.setText("");
		textview3.setText("");
		textview4.setText("");
		textview5.setText("");
		textview6.setText("");
		textview7.setText("");
	    edit1.setText("");
	    edit2.setText("");
	    if(water!=null){
	    	textview1.setText(water.getName());
	    	textview2.setText(water.getWaternumber());
	    	textview3.setText(water.getWateradds());
	    	textview4.setText(water.getWaterproperties());
	    	textview5.setText(water.getMetercaliber());
	    	textview6.setText(water.getLastmonthwater()+"");
	    	if(water.getThismonthwater()>0){
	    		edit1.setText(water.getThismonthwater()+"");
	    		edit2.setText(water.getDesc());
	    		textview7.setText(water.getThismonthwater()-water.getLastmonthwater()+"");
	    	}
	    }
		
	}
	@Override
	public void onClick(View v) {
		if(v.getId()==button1.getId()){
			if(water!=null){
				System.out.println("拍照");
				Intent intent=new Intent(ReviewNoRfidActivity.this, ImageSwitcherActivity.class);				
				Bundle bundle=new Bundle();				
				bundle.putString("otherid", waterid);
				bundle.putString("status", "3");
				bundle.putString("classname", "ReviewNoRfidActivity");
				intent.putExtras(bundle);
				startActivity(intent);			
			}
		}else if(v.getId()==button2.getId()){
			if(water.getIsupload().equals("1")){
				Toast.makeText(this, "已经上传过了，不能再抄了", 1000).show();
				return;
			}
			if(TextUtils.isEmpty(edit1.getEditableText().toString())){
				Toast.makeText(this, "还没抄表不能保存", 1000).show();
				return;
			}
			if(isupload){
				Toast.makeText(this, "已经上传了，不能再保存", 1000).show();
				return;
			}
			boolean b=save();
			if(b){
				Toast.makeText(this, "抄表成功", 1000).show();
				issave=true;
				return;
			}else{
				Toast.makeText(this, "保存失败", 1000).show();
				issave=false;
				return;
			}
		}else if(v.getId()==button3.getId()){

			if(isupload){
				Toast.makeText(ReviewNoRfidActivity.this, "已经上传过了", 1000).show();
				return;
			}
			if(!issave){
				Toast.makeText(ReviewNoRfidActivity.this, "请保存后再上传！", 1000).show();
				return;
			}
			ReviewDataDao dao=new ReviewDataDao(ReviewNoRfidActivity.this);
			final SharedPreferenceUtil sh=new SharedPreferenceUtil(ReviewNoRfidActivity.this);
			 waterinfo=dao.queryOneNoUpload(waterid);
			 
			dao.close();
			pd=new ProgressDialog(ReviewNoRfidActivity.this);
			pd.setMessage("上传中......");
			pd.show();
			new Thread(){


				@Override
				public void run() {
					
					Map<String, String> map=new HashMap<String, String>();
					
					Map<File, String> mapfile=new HashMap<File, String>();
					Map<String, String> map1=new HashMap<String, String>();
					map1.put("waternumber", waterinfo.getWaternumber());
		            map1.put("usewater", waterinfo.getThismonthwater()-waterinfo.getLastmonthwater()+"");
					map1.put("imsi", sh.getValue(XmlNameHelper.IMSI));
					map1.put("thismonthwater", waterinfo.getThismonthwater()+"");
					map1.put("thisdate", waterinfo.getThisdate());
					map1.put("desc", waterinfo.getDesc());
					map1.put("sid", waterinfo.getSid());
					List<String> list=waterinfo.getImagepath();
					for(int k=0;k<list.size();k++){
						File file=new File(list.get(k));
						if(file.exists()){
							mapfile.put(file, "imagepath");
							map.put(file.getName(), "imagename");
						}
					}
					RequestUrl re=new RequestUrl(ReviewNoRfidActivity.this);
				String respon=	UploadHttpClient.uploadSubmit(re.getUrl(RequestUrl.COPYWATERLIST), map, mapfile,map1);
				if(respon.equals("error")){
					Message msg=myHandler.obtainMessage();
					msg.what=1;
					myHandler.sendMessage(msg);
				}else{
					try {
						JSONObject json=new JSONObject(respon);
						String message=json.getString("message");
						if(message.equals("yes")){
							Message msg=myHandler.obtainMessage();
							msg.what=2;
							myHandler.sendMessage(msg);
						}else{
							Message msg=myHandler.obtainMessage();
							msg.what=3;
							myHandler.sendMessage(msg);
						}
					} catch (JSONException e) {
					       
						Message msg=myHandler.obtainMessage();
						msg.what=3;
						myHandler.sendMessage(msg);
					}
					
				}
					
				}
				
			
			}.start();
		
		}
		
	}
	
	/**
	 * 保存
	 * 
	 * @return
	 */
	public boolean save() {
		boolean b=false;
		if (water.getIsupload().equals("1")) {
			Toast.makeText(ReviewNoRfidActivity.this, "已经上传过了不能再抄了", 1000).show();
			return false;
		}
		ReviewDataDao dao = new ReviewDataDao(this);
		b = dao.isPhotograph(water.getWaterid());
		if (!b) {
			Toast.makeText(ReviewNoRfidActivity.this, "读卡异常抄表需拍照", 1000).show();
			dao.close();
			return false;
		}

		if(water!=null){
			Double thismothwater = Double.parseDouble(edit1.getEditableText()
					.toString());
			String desc=edit2.getEditableText().toString();
			
			 b=dao.saveWater(waterid, thismothwater,desc,"1");
			 dao.close();
		}
		
		
		return b;

	}
	/**
	 * 上传消息处理
	 */
	Handler myHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			
			if(msg.what==2){
				pd.dismiss();
				Toast.makeText(ReviewNoRfidActivity.this, "上传成功", 1000).show();
				CopyWaterDao dao=new CopyWaterDao(ReviewNoRfidActivity.this);
				dao.uploadstatus(waterid);
				
				dao.close();
				isupload=true;
				
			}else{
				pd.dismiss();
				Toast.makeText(ReviewNoRfidActivity.this, "上传失败", 1000).show();
				isupload=true;
			}
			super.handleMessage(msg);
		}
		
	};
	
	
}
